source("functions.R")
Hallmark_module_UI<-function(id)
{
  ns<-NS(id)
  tagList(
    bscols(widths = 10,div(style="height: 15px;",width = '200px')),
    fluidRow(column(10,DT::dataTableOutput(ns("Enriched_hall")))),
    br(),
    hr(),
    br(),
    fluidRow(
      column(1,
             selectInput(ns("datachoice11")  ,label = h5("Select Data Type"), 
                         choices = list("Excel" = 1, "CSV" = 2),
                         selected = 1)),
      column(1, 
             br(),
             br(),
             downloadButton(ns('download_Enriched_hall_Table'), 'Download Enriched Hallmarks Table'))),
    #downloadButton(ns('download_Enriched_hall_Table'), 'Download full Data'),
    DT::dataTableOutput(ns("filtered_hall")),
    br(),
    br(),
    hr(),
    br(),
    uiOutput(ns("plot_option_hall")),
    uiOutput(ns("plot_category_hall")),
    downloadButton(ns('download_hall_plot'), 'Download Plot'),
    plotOutput(ns("hall"))
  )
  
}

Hallmark_module<-function(input,output,session,DE_genes,
                          organism,dds.fc,combination,wgcna_output)
{
  #Compute the molecular signatures based on a list for a list of DE genes(Uses function enrichr from clusterprofiler)
  #Construct  a matrix where row->comparison A vs B, C vs D .etc
  # columns (up regulated hallmark, down regulated hallmark)
  #Loop through a similar matrix generated by reactive DE_genes)
  #Filter hallmarks for each element in the matrix generated by reactive DE_genes
  #Please check msig database for more information on hallmark gene sets
  
  combo<-combination()
  print(combo())
  num<-length(combo())
  
  Enriched_hall<-reactive({
    c1_hallmark <- read.gmt("./www/h.all.v5.1.entrez.gmt")
    print("inside hallmark line 39")
    print(organism())
    result<-DE_genes()
    
    if(!is.null(wgcna_output()))
    {
      if((length(wgcna_output()$modules())>0))
      {
        num<-length(combo())
        enrichment_main("hallmark",result(),organism(),dds.fc(),
                        num,wgcna_output()$modules(),wgcna_output()$WGCNA_matrix(),c1_hallmark)
      }
    }
    else
    {
      print("inside hallmark line 53")
      #print(head(result()))
      print(combination())
      print(unlist(combination()))
      combo<-combination()
      print(combo())
      num<-length(combo())
      print(combo())
      print(num)
      enrichment_main("hallmark",result(),organism(),dds.fc(),
                      num,NULL,NULL,c1_hallmark)
    }
  })
  
  
  
#Display summary of hallmark gene sets identified for selected comparisons
  
  output$Enriched_hall <- DT::renderDataTable({
    
      result<-Enriched_hall()[[1]]
      #print(head(result))
      num <- length(combo())
      rows<-num
      modules<-NULL
      WGCNA_matrix<-NULL
      res<-NULL#data.frame(matrix(NA, nrow = num, ncol = 3))
      
      if(!is.null(wgcna_output()))
      {
        if((length(wgcna_output()$modules())>0))
        {
          modules<-as.data.frame(table(wgcna_output()$modules()))
          colnames(modules)<-c("Var1","numbers")
          entry<-c(as.vector(combo()), as.vector(modules$Var1))
          # print(modules$Var1)
          print(entry)
          rows<-length(entry)
          
          res<-data.frame(matrix(NA, nrow = rows, ncol = 3))
          colnames(res)<-c('Up regulated','Down regulated','Regulated')
          
          
          print(modules$Var1)
          #print(entry)
          rownames(res)<-lapply(1:rows, function(i) {
            unlist(entry[i])
            
          })
          for(i in 1:length(combo()))
          {
            #print(nrow(as.data.frame(result[[i]][1])))
            res[i,1]<-nrow(as.data.frame(result[[i]][[1]]))
            res[i,2]<-nrow(as.data.frame(result[[i]][[2]]))
            res[i,3]<-0
          }
          
          for(i in 1+length(combo()):nrow(modules))
          {
            #print(nrow(as.data.frame(result[[i]][1])))
            print('res')
            print(result[[i]][[3]])
            res[i,1:2]<-0
            res[i,3]<-nrow(as.data.frame(result[[i]][3]))
            
          }
        }
      }
      else{
        #num <- length(combination())
        num <-length(combo())
        res<-data.frame(matrix(NA, nrow = length(combo()), ncol = 2))
        rownames(res)<-lapply(1:length(combo()), function(i) {
          #combo()[[i]]
          # if(num==1) combo()
          combo()[[i]]
          #paste(combination()[[i]][1],' vs ',combination()[[i]][2])
        })
        colnames(res)<-c('Enriched hallmark for Up-reg genes','Enriched hallmark for Down-reg genes')
        #print(res)
        #print(res[1,1])
        for(i in 1:length(combo()))
        {
          print(nrow(as.data.frame(result[[i]][[1]])))
          res[i,1]<-nrow(as.data.frame(result[[i]][[1]]))
          res[i,2]<-nrow(as.data.frame(result[[i]][[2]]))
        }
      }
      #print(res)
      DT::datatable(res,class = 'cell-border stripe',
                    selection = list(mode='single',target = 'cell'),
                    extensions = list('Scroller'=NULL,'Buttons'=NULL),
                    options = list(deferRender = TRUE,scrollX = TRUE,scrollY = 150,scroller = TRUE,dom = 'Bfrtip',
                                   buttons = list('copy', list(extend = 'collection',buttons = c('csv', 'excel', 'pdf'),
                                                               text = 'Download table'))),#I('colvis')
                    
                    escape = FALSE
      )
    
  })
  #Display hallmark genes for the selected comparison
  observeEvent(input$Enriched_hall_cell_clicked,{
    print('hey')
    print(input$Enriched_hall_cells_selected)
    print(input$Enriched_hall_cell_clicked)
    selected <- input$Enriched_hall_cells_selected
    row<-selected[1]
    print('row')
    print(row)
    col<-selected[2]
    print('col')
    print(col)
    if(length(selected)>0){
      
      output$filtered_hall <- DT::renderDataTable({
        print('hey')
        result<-Enriched_hall()[[1]]
        df<-as.data.frame(result[[row]][[col]])
        print(head(df))
        
        DT::datatable(df,class = 'cell-border stripe',
                      selection = list(target = 'column'),
                      extensions = list('Scroller'=NULL,'Buttons'=NULL),
                      options = list(deferRender = TRUE,scrollX = TRUE,scrollY = 150,scroller = TRUE,dom = 'Bfrtip',
                                     buttons = list('copy')))
        
      })
      #download button
      output$download_Enriched_hall_Table <- downloadHandler(
        
        filename = function() 
        {
          if(as.numeric(input$datachoice11==1)){
          #condition<-paste(combination()[[row]][1],' vs ',combination()[[row]][2]) 
          condition <-combo()[[row]]
          if(col==1) paste('Up regulated hallmark for ',condition,'.xlsx')
          else if(col==2) paste('Down regulated hallmark for ',condition,'.xlsx')
          else if(col==3) paste('regulated hallmark for ',condition,'.xlsx')
          }
          else {
            condition <-combo()[[row]]
            if(col==1) paste('Up regulated hallmark for ',condition,'.csv')
            else if(col==2) paste('Down regulated hallmark for ',condition,'.csv')
            else if(col==3) paste('regulated hallmark for ',condition,'.csv')
          }
        },
        content = function(file) {
          #sort by adjusted p value.
          print('heyho')
          result<-Enriched_hall()[[1]]
          df<-as.data.frame(result[[row]][[col]])
          
          nam<-"Sheet 1"
          condition <-combo()[[row]]
          condition<-str_replace_all(condition,"[^[:alnum:]]",".")
          if(col==1) nam<-paste('Up regulated hallmark for ',condition)
          else if(col==2) nam<-paste('Down regulated hallmark for ',condition)
          else if(col==3) nam<-paste('regulated hallmark for ',condition)
          
          if(as.numeric(input$datachoice11==1)){
            M <- as.matrix(df)
            wb <- createWorkbook()
            addWorksheet(wb, sheetName = "Hallmark table")
            writeData(wb = wb, sheet = 1, x = M, colNames = T, rowNames = T)
            saveWorkbook(wb, file)
          # write.xlsx2(df, file, sheetName = nam,
          #             col.names = TRUE, row.names = TRUE, append = FALSE)
          }
          else {
            write.csv(df, file)
          }
        }
        
      )
      
      output$plot_category_hall<-renderUI({
        textInput(session$ns("category_hall"),label = h6("Enter number of categories to display"), 
                  value = "10") 
      })

      print(as.numeric(input$category_hall))
      
      #Display top 10 halmark plots for the selected comparison    
      hallplot<-reactive(
      {
        
        result<-Enriched_hall()[[2]] #obj
        res<-Enriched_hall()[[1]]
        #input$category
        #input$plot_k
        #enrichment input
        #category_go
        #input$plotType_bp (plot_type)
        #input$category_bp category
        req(input$category_hall)
        
        if(nrow(res[[row]][[col]]) == 0){
          warning("No Data available for plotting")
        }
        else if(nrow(res[[row]][[1]]) == 0 && nrow(res[[row]][[2]] != 0)){
          enrichment_plot("hallmark",result,res,row,1,input$category_hall,NULL)
        }
        else{
          enrichment_plot("hallmark",result,res,row,col,input$category_hall,NULL)
        } 
      })

      output$hall<- renderPlot({
        hallplot()
      })
      #Download hallmark plot
      output$download_hall_plot <- downloadHandler(
        
        filename =function()
        {
          condition <-combo()[[row]]
          if(col==1) paste('Barplot of Up regulated hallmarkP for ',condition,'.svg')
          else if(col==2) paste('Barplot of Down regulated hallmark for ',condition,'.svg')
        },
        content = function(file) {
          req(input$category_hall)
          ggsave(file,hallplot())#,width=800, height=500)
          
          
          #dev.off()
          
          
        })
    }
  })
return(list(
  Enriched_hall_table=reactive({Enriched_hall()[[1]]}),
  Enriched_hall_obj=reactive({Enriched_hall()[[2]]})
))
}